package gold.digger;

import java.util.*;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC729 {
    public long startExecuteTime = System.currentTimeMillis();


    class MyCalendar {

        public TreeMap<Integer, Integer> record = new TreeMap<>();

        public MyCalendar() {

        }

        public boolean book(int start, int end) {
            if (record.size() <= 0) record.put(start, end);
            else {
                Integer ceilingKey = record.ceilingKey(start), floorKey = record.floorKey(start);
                if (null == ceilingKey && null != floorKey) {
                    if (record.get(floorKey) > start) return false;
                    if (record.get(floorKey) == start) record.put(floorKey, end);
                    else record.put(start, end);
                } else if (null != ceilingKey && null == floorKey) {
                    if (ceilingKey < end) return false;
                    if (ceilingKey == end) {
                        record.put(start, record.get(ceilingKey));
                        record.remove(ceilingKey);
                    } else record.put(start, end);
                } else {
                    // 前后端都不为空，判断较为复杂
                    if (record.get(floorKey) > start) return false;
                    if (ceilingKey < end) return false;
                    if (record.get(floorKey) == start && ceilingKey == end) {
                        record.put(floorKey, record.get(ceilingKey));
                        record.remove(ceilingKey);
                        return true;
                    }

                    if (record.get(floorKey) == start) record.put(floorKey, end);
                    else if (ceilingKey == end) {
                        record.put(start, record.get(ceilingKey));
                        record.remove(ceilingKey);
                    } else record.put(start, end);
                }
            }

            return true;
        }
    }


    public void run() {
        MyCalendar solution = new MyCalendar();
        System.out.println(solution.book(37, 50));
        System.out.println(solution.book(33, 50));
        System.out.println(solution.book(4, 17));
        System.out.println(solution.book(35, 48));
        System.out.println(solution.book(8, 25));
    }

    public static void main(String[] args) throws Exception {
        LC729 an = new LC729();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
